package com.example.spring.dao;

import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.example.spring.form.Contact;

@Repository
public class ContactDAOImpl implements ContactDAO{

	@Autowired
    private SessionFactory sessionFactory;
	
	public void setSessionFactory(SessionFactory sessionFactory){
		this.sessionFactory = sessionFactory;
	}
	
	@Override
	public void addContact(Contact contact) throws HibernateException {
		Session session = sessionFactory.openSession();
		Transaction transaction = session.beginTransaction();
		try{
			session.save(contact);
			transaction.commit();
		}
		catch(HibernateException e){
			e.printStackTrace();
			if(transaction != null){
				transaction.rollback();
			}
			throw e;
		}
		finally{
			if(session != null){
				session.close();
			}
		}
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Contact> listContact() {
		Session session = sessionFactory.openSession();
		Transaction transaction = session.beginTransaction();
		List<Contact> contactList = null;
		try{
			contactList = session.createQuery("from Contact").list();
			transaction.commit();
		}
		catch(HibernateException e){
			e.printStackTrace();
			if(transaction != null){
				transaction.rollback();
			}
		}
		finally{
			if(session != null){
				session.close();
			}
		}
		return contactList;
	}

	@Override
	public void removeContact(Integer id) {
		Session session = sessionFactory.openSession();
		Transaction transaction = session.beginTransaction();
		try{
			Contact contact = (Contact) session.load(Contact.class, id);
	        if (null != contact) {
	        	session.delete(contact);
	        }
	        transaction.commit();
		}
		catch(HibernateException e){
			e.printStackTrace();
			if(transaction != null){
				transaction.rollback();
			}
		}
		finally{
			if(session != null){
				session.close();
			}
		}
	}

}
